#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
截图工具类
负责生成和管理截图证据
"""

import os
import logging
from datetime import datetime
from typing import Optional

logger = logging.getLogger(__name__)

class EvidenceCapturer:
    """
    截图证据收集器，生成操作证据截图
    """
    
    def __init__(self, screenshot_dir: str):
        """
        初始化截图工具
        
        Args:
            screenshot_dir: 截图存储目录
        """
        self.screenshot_dir = screenshot_dir
        self.browser = None  # 实际项目中需要传入浏览器控制实例
        os.makedirs(screenshot_dir, exist_ok=True)
    
    def set_browser(self, browser):
        """设置浏览器实例"""
        self.browser = browser
    
    def capture_sequence(self, user_id: str, step_name: str) -> bool:
        """
        捕获操作序列的截图
        
        Args:
            user_id: 用户ID
            step_name: 当前步骤名称
            
        Returns:
            bool: 截图是否成功
        """
        if not self.browser:
            logger.error("浏览器实例未初始化，无法截图")
            return False
        
        try:
            # 创建时间戳目录
            timestamp = self._get_timestamp(format="%Y%m%d_%H%M%S")
            session_dir = os.path.join(self.screenshot_dir, f"{user_id}/{timestamp}")
            os.makedirs(session_dir, exist_ok=True)
            
            # 截图文件路径
            screenshot_path = os.path.join(session_dir, f"{step_name}.png")
            
            # 高亮当前操作元素
            self._highlight_active_element()
            
            # 滚动到操作区域
            self._scroll_to_active_area()
            
            # 执行截图
            self.browser.save_screenshot(screenshot_path)
            
            logger.info(f"成功保存截图: {screenshot_path}")
            return True
            
        except Exception as e:
            logger.error(f"截图失败: {e}")
            return False
        finally:
            # 移除高亮效果
            self._remove_highlight()
    
    def capture_with_annotations(self, user_id: str, step_name: str, annotations: dict) -> bool:
        """
        带注释的截图
        
        Args:
            user_id: 用户ID
            step_name: 当前步骤名称
            annotations: 注释信息
            
        Returns:
            bool: 截图是否成功
        """
        if not self.browser:
            logger.error("浏览器实例未初始化，无法截图")
            return False
        
        try:
            # 创建时间戳目录
            timestamp = self._get_timestamp(format="%Y%m%d_%H%M%S")
            session_dir = os.path.join(self.screenshot_dir, f"{user_id}/{timestamp}")
            os.makedirs(session_dir, exist_ok=True)
            
            # 截图文件路径
            screenshot_path = os.path.join(session_dir, f"{step_name}_annotated.png")
            
            # 添加注释
            self._add_annotations(annotations)
            
            # 执行截图
            self.browser.save_screenshot(screenshot_path)
            
            logger.info(f"成功保存带注释的截图: {screenshot_path}")
            return True
            
        except Exception as e:
            logger.error(f"带注释截图失败: {e}")
            return False
        finally:
            # 移除注释
            self._remove_annotations()
    
    def _highlight_active_element(self):
        """高亮当前活跃元素"""
        try:
            # 使用JavaScript高亮当前活跃元素
            highlight_script = """
            (function() {
                var active = document.activeElement;
                if (active) {
                    active.oldBorder = active.style.border;
                    active.oldBackground = active.style.backgroundColor;
                    active.style.border = '2px solid red';
                    active.style.backgroundColor = 'rgba(255, 0, 0, 0.1)';
                }
                return true;
            })();
            """
            self.browser.execute_script(highlight_script)
        except Exception as e:
            logger.error(f"高亮元素失败: {e}")
    
    def _remove_highlight(self):
        """移除高亮效果"""
        try:
            # 使用JavaScript移除高亮效果
            remove_highlight_script = """
            (function() {
                var active = document.activeElement;
                if (active && active.oldBorder !== undefined) {
                    active.style.border = active.oldBorder;
                    active.style.backgroundColor = active.oldBackground;
                }
                return true;
            })();
            """
            self.browser.execute_script(remove_highlight_script)
        except Exception as e:
            logger.error(f"移除高亮失败: {e}")
    
    def _scroll_to_active_area(self):
        """滚动到活跃区域"""
        try:
            # 使用JavaScript滚动到活跃元素
            scroll_script = """
            (function() {
                var active = document.activeElement;
                if (active) {
                    active.scrollIntoView({
                        behavior: 'smooth',
                        block: 'center'
                    });
                }
                return true;
            })();
            """
            self.browser.execute_script(scroll_script)
            
            # 等待滚动完成
            import time
            time.sleep(0.4)
            
        except Exception as e:
            logger.error(f"滚动到活跃区域失败: {e}")
    
    def _add_annotations(self, annotations: dict):
        """
        添加注释信息
        
        Args:
            annotations: 注释信息字典
        """
        try:
            # 转换注释为JavaScript可用格式
            annotation_str = str(annotations).replace("'", '"')
            
            # 使用JavaScript添加注释
            add_annotations_script = f"""
            (function() {{
                var annotations = {annotation_str};
                var annotationDiv = document.createElement('div');
                annotationDiv.id = 'screenshot-annotations';
                annotationDiv.style.position = 'fixed';
                annotationDiv.style.top = '10px';
                annotationDiv.style.right = '10px';
                annotationDiv.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
                annotationDiv.style.color = 'white';
                annotationDiv.style.padding = '10px';
                annotationDiv.style.borderRadius = '5px';
                annotationDiv.style.zIndex = '9999';
                annotationDiv.style.maxWidth = '300px';
                
                var content = '<h3>操作信息</h3><ul>';
                for (var key in annotations) {{
                    content += '<li><strong>' + key + ':</strong> ' + annotations[key] + '</li>';
                }}
                content += '</ul>';
                annotationDiv.innerHTML = content;
                
                document.body.appendChild(annotationDiv);
                return true;
            }})();
            """
            self.browser.execute_script(add_annotations_script)
        except Exception as e:
            logger.error(f"添加注释失败: {e}")
    
    def _remove_annotations(self):
        """移除注释信息"""
        try:
            # 使用JavaScript移除注释
            remove_annotations_script = """
            (function() {
                var annotationDiv = document.getElementById('screenshot-annotations');
                if (annotationDiv) {
                    annotationDiv.parentNode.removeChild(annotationDiv);
                }
                return true;
            })();
            """
            self.browser.execute_script(remove_annotations_script)
        except Exception as e:
            logger.error(f"移除注释失败: {e}")
    
    def _get_timestamp(self, format: str = "%Y-%m-%d %H:%M:%S") -> str:
        """
        获取当前时间戳
        
        Args:
            format: 时间格式字符串
            
        Returns:
            str: 格式化的时间戳
        """
        return datetime.now().strftime(format) 